<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #childList>
        <a-button class="mt-2 btn" @click="handleChildListAdd" v-if="isShow">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('添加合同') }}
        </a-button>
        <BasicTable @register="registerChildListTable" @row-click="handleChildListRowClick">
          <template #childListIsum="{ record: childRecord }">
            <a-input v-model:value="childRecord.isum" :disabled="!childRecord.showCol" />
          </template>
          <template #childListIsum2="{ record: childRecord }">
            <a-input v-model:value="childRecord.isum2" :disabled="!childRecord.showCol" />
          </template>
          <template #childListIsum3="{ record: childRecord }">
            <a-input v-model:value="childRecord.isum3" :disabled="!childRecord.showCol" />
          </template>
          <template #childListUpload="{ record: childRecord }">
            <BasicUpload
              v-model:value="childRecord.dataMap"
              :bizKey="childRecord.id"
              :bizType="'pmContract2_file'"
              :uploadType="'all'"
              :loadTime="record.__t"
              :isPreview="false"
              :disabled="!isShow"
            />
          </template>
        </BasicTable>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsProjContractPmContract2UploadBatchForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { BasicUpload } from '/@/components/Upload';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmContract2,
    pmContract2Save,
    pmContract2Form,
    pmContract2UploadBatch,
  } from '/@/api/proj/contract/pmContract2';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';

  const emit = defineEmits(['success', 'register']);
  const { hasPermission } = usePermission();

  const { t } = useI18n('proj.contract.pmContract2');
  const { showMessage } = useMessage();
  const record = ref<PmContract2>({} as PmContract2);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增工程项目合同') : t('编辑工程项目合同'),
  }));

  let isShow = ref(false);
  // 假设您有一个变量来存储当前编辑行的 ID
  let currentEditingRowId = ref(null);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('项目名称'),
      field: 'prono',
      fieldLabel: 'proname',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationTreeData,
        params: {},
        canSelectParent: false,
        allowClear: false,
        disabled: computed(() => !isShow.value),
      },
      required: true,
    },
    {
      label: t('存档编号'),
      field: 'contractNo',
      component: 'Input',
      componentProps: {
        disabled: computed(() => !isShow.value),
      },
      //required: true,
    },
    {
      label: t('合同分类'),
      field: 'clsCode',
      component: 'Select',
      componentProps: {
        dictType: 'zf_constract_cls',
        allowClear: true,
      },
      required: true,
      itemProps: { validateTrigger: 'blur' },
      ifShow: false,
    },
    {
      label: t('合同编号'),
      field: 'code',
      component: 'Input',
      required: true,
      itemProps: { validateTrigger: 'blur' },
      ifShow: false,
    },
    {
      label: t('合同名称'),
      field: 'name',
      component: 'Input',
      required: true,
      itemProps: { validateTrigger: 'blur' },
      ifShow: false,
    },
    {
      label: t('新增合同'),
      field: 'childList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'childList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerChildListTable, childListTable] = useTable({
    actionColumn: {
      width: 40,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleChildListDelete.bind(this, record),
          },
          // auth: 'proj:xj:pmInspection:edit',
          ifShow: isShow.value,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showIndexColumn: true,
  });

  async function setChildListTableData(_res: Recordable) {
    childListTable.setColumns([
      {
        title: t('合同类型'),
        dataIndex: 'ctype',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'zf_constract_type',
          allowClear: true,
          onChange: (v, _res: Recordable) => {
            console.log(v, 'v', currentEditingRowId.value);
            // childListTable.updateTableDataRecord(record.value.id,{
            //   showCol: v == '3' ? true : false
            // })
            // 如果v为3,合同金额editRow: true
            if (v == '3' && currentEditingRowId.value !== null) {
              childListTable.updateTableDataRecord(currentEditingRowId.value, {
                showCol: true,
              });
            }
          },
        },
        editRule: true,
      },
      {
        title: t('附件上传'),
        dataIndex: 'upload',
        width: 120,
        align: 'left',
        slot: 'childListUpload',
      },
      {
        title: t('合同金额'),
        dataIndex: 'isum',
        width: 120,
        align: 'left',
        slot: 'childListIsum',
        editRule: (text: any, record: Recordable) => {
          return new Promise((resolve, reject) => {
            // 正则匹配请输入一个数值
            let reg = /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/;
            if (reg.test(text)) {
              resolve();
            } else {
              reject('请输入一个数值！');
            }
          });
        },
      },
      {
        title: t('安全文明措施费'),
        dataIndex: 'isum2',
        width: 120,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        slot: 'childListIsum2',
        editRule: (text: any, record: Recordable) => {
          return new Promise((resolve, reject) => {
            // 正则匹配请输入一个数值
            let reg = /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/;
            if (reg.test(text)) {
              resolve();
            } else {
              reject('请输入一个数值！');
            }
          });
        },
      },
      {
        title: t('监理费'),
        dataIndex: 'isum3',
        width: 120,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        slot: 'childListIsum3',
        editRule: (text: any, record: Recordable) => {
          return new Promise((resolve, reject) => {
            // 正则匹配请输入一个数值
            let reg = /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/;
            if (reg.test(text)) {
              resolve();
            } else {
              reject('请输入一个数值！');
            }
          });
        },
      },
    ]);
    childListTable.setTableData(record.value.childList || []);
  }

  function handleChildListRowClick(record: Recordable) {
    currentEditingRowId.value = record.id;
    record.onEdit?.(true, false);
  }
  function handleChildListAdd() {
    childListTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
      showCol: false,
      ids: new Date().getTime(),
    });
  }
  function handleChildListDelete(record: Recordable) {
    childListTable.deleteTableDataRecord(record);
  }
  async function getChildList() {
    let childListValid = true;
    let childList: Recordable[] = [];
    for (const record of childListTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        childListValid = false;
      }
      childList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of childListTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      childList.push({
        ...record,
        status: '1',
      });
    }
    if (!childListValid) {
      throw { errorFields: [{ name: ['childList'] }] };
    }
    return childList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmContract2Form(data);
    record.value = (res.pmContract2 || {}) as pmContract2;

    record.value.__t = new Date().getTime();
    console.log('record.value', record.value);
    if (record.value.ctype == '3') {
      record.value.showCol = true;
    } else {
      record.value.showCol = false;
    }

    setFieldsValue(record.value);
    setChildListTableData(res);

    isShow.value = record.value.isNewRecord ? true : false;

    setDrawerProps({
      loading: false,
      // showOkBtn: isShow.value && hasPermission(['proj:xj:pmInspection:edit']),
    });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.parent = {
        contractNo: data.contractNo,
        code: data.code,
        name: data.name,
        clsCode: data.clsCode,
        proname: data.proname,
        prono: data.prono,
      };
      data.childList = await getChildList();
      // console.log('submit', params, data, record);
      const res = await pmContract2UploadBatch(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style scoped>
  /deep/.jeesite-basic-table .ant-table-content {
    min-height: 40vh;
  }

  .btn {
    margin-bottom: 8px;
  }
</style>
